package com.shows.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shows.auto.JSONAuthentication;
import com.shows.entity.ShDress;
import com.shows.entity.ShOrder;
import com.shows.entity.ShUser;
import com.shows.mapper.ShDressMapper;
import com.shows.mapper.ShOrderMapper;
import com.shows.mapper.ShUserMapper;
import com.shows.response.Result;
import com.shows.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author animal
 * @since 2022-02-24
 */
@RestController
@RequestMapping("/sh-dress")
public class ShDressController extends JSONAuthentication {
    @Autowired
    ShDressMapper shDressMapper;
    @Autowired
    ShUserMapper shUserMapper;
    @Autowired
    ShOrderMapper shOrderMapper;

    @ApiOperation(value = "添加租赁衣服")
    @PostMapping("/add")
    public void addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("price") float price,@RequestParam("tsName") String tsName,@RequestParam("content") String content) throws Exception {
        ShDress shDress = new ShDress();
        shDress.setPrice(price);
        shDress.setTsName(tsName);
        shDress.setContent(content);
        byte[] bytes = file.getBytes();
        String imageFileName = file.getOriginalFilename();
        String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
        Path path = Paths.get("D:\\自己的项目\\流浪动物救助\\adopt\\adopt\\src\\assets\\picture\\" + fileName);
        //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
        Files.write(path, bytes);//写入文件
        String avatar_url = fileName;
        shDress.setPicture(avatar_url);
        response.reset();
        if (shDressMapper.insert(shDress) > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "删除租赁衣服")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        int i = shDressMapper.deleteById(id);
        if (i > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "修改祖农衣服价格")
    @PostMapping("/updPrice")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id, @RequestParam("price") float price) throws Exception {
        ShDress shDress = shDressMapper.selectById(id);
        shDress.setPrice(price);
        if (shDressMapper.updateById(shDress) > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "通过租赁衣服id查询衣服")
    @PostMapping("/findByName")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {

        ShDress shDress = shDressMapper.selectById(id);

        if (shDress != null) {
            if (shDress.getUserId() != 0) {
                shDress.setShUser(shUserMapper.selectById(shDress.getUserId()));
            }
            Result ok = Result.ok().data("dress", shDress);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "查找所有衣服")
    @PostMapping("/findAllDress")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        Page<ShDress> shUserPage = new Page<>(current, size);
        Page<ShDress> shUserPages = shDressMapper.selectPage(shUserPage, null);
        List<ShDress> records = shUserPages.getRecords();
        int total = shDressMapper.selectCount(null);
        for (ShDress a : records) {
            if (a.getUserId() != 0) {
                a.setShUser(shUserMapper.selectById(a.getUserId()));
            }
        }
        if (records.size() > 0) {
            Result ok = Result.ok().data("dressList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "出租衣服")
    @PostMapping("/ChuZhuDressByid")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id, @RequestParam("userId") int userId, @RequestParam("status") int status) throws Exception {
        ShUser shUser = shUserMapper.selectById(userId);
        Float balance = shUser.getBalance();
        ShDress shDress = shDressMapper.selectById(id);
        if (balance - shDress.getPrice() < 0) {
            Result error = Result.error().message("余额不足,请充值");
            this.WriteJSON(request, response, error);
        } else {

            shDress.setStatus(status);
            shDress.setUserId(userId);
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            shDress.setUpdTime(timestamp);
            if (shDressMapper.updateById(shDress) > 0) {
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }

    }

    @ApiOperation(value = "归还衣服")
    @PostMapping("/GuiHuanDressByid")
    public void findByIdb(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id,@RequestParam("userId") int userId) throws Exception {
        ShDress shDress = shDressMapper.selectById(id);
        shDress.setStatus(0);
        shDress.setUserId(-1);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        shDress.setGhTime(timestamp);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("dr_id",id);
        wrapper.eq("user_id",userId);
        ShOrder shOrder = shOrderMapper.selectOne(wrapper);
        shOrder.setStatus("已归还");
        if (shDressMapper.updateById(shDress) > 0&&shOrderMapper.updateById(shOrder)>0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error().message("归还错误，请联系管理员");
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "查找所有衣服通过衣服名字")
    @PostMapping("/findAllDressBytsName")
    public void dd(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current, @RequestParam("tsName") String tsName) throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("ts_name", tsName);
        Page<ShDress> shUserPage = new Page<>(current, size);
        Page<ShDress> shUserPages = shDressMapper.selectPage(shUserPage, wrapper);
        List<ShDress> records = shUserPages.getRecords();
        int total = shDressMapper.selectCount(null);
        for (ShDress a : records) {
            if (a.getUserId() != 0) {
                a.setShUser(shUserMapper.selectById(a.getUserId()));
            }
        }
        if (records.size() > 0) {
            Result ok = Result.ok().data("dressList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }

    }

    @ApiOperation(value = "修改衣服名字")
    @PostMapping("/updTName")
    public void updUseraaa(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id, @RequestParam("tsName") String tsName) throws Exception {
        ShDress shDress = shDressMapper.selectById(id);
        shDress.setTsName(tsName);
        if (shDressMapper.updateById(shDress) > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }

    }

    @ApiOperation(value = "修改衣服介绍")
    @PostMapping("/updTcontent")
    public void updUseraaad(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id, @RequestParam("content") String content) throws Exception {
        ShDress shDress = shDressMapper.selectById(id);
        shDress.setTsName(content);
        if (shDressMapper.updateById(shDress) > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有租借衣服通过用户id")
    @PostMapping("/findAllDressByUserID")
    public void findAllDressByUserID(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current, @RequestParam("userId") int  userId) throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("user_id", userId);
        Page<ShDress> shUserPage = new Page<>(current, size);
        Page<ShDress> shUserPages = shDressMapper.selectPage(shUserPage, wrapper);
        List<ShDress> records = shUserPages.getRecords();
        int total = shDressMapper.selectCount(null);
        for (ShDress a : records) {
            if (a.getUserId() != 0) {
                a.setShUser(shUserMapper.selectById(a.getUserId()));
            }
        }
        if (records.size() > 0) {
            Result ok = Result.ok().data("dressList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }

    }
    @ApiOperation(value = "查找所有未租用的衣服")
    @PostMapping("/findAllNoZy")
    public void findAllNoZy(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("status",0);
        Page<ShDress> shUserPage = new Page<>(current, size);
        Page<ShDress> shUserPages = shDressMapper.selectPage(shUserPage, wrapper);
        List<ShDress> records = shUserPages.getRecords();
        int total = shDressMapper.selectCount(wrapper);
        for (ShDress a : records) {
            if (a.getUserId() != 0) {
                a.setShUser(shUserMapper.selectById(a.getUserId()));
            }
        }
        if (records.size() > 0) {
            Result ok = Result.ok().data("dressList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
}